/* BSD Socket API Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include <sys/param.h>
#include "DevicesQueue.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"

#include "lwip/sockets.h"
#include <lwip/netdb.h>

#include "taskNetwork.h"


static const char *TAG = __FILE_NAME__;

/* crc_modbus[udp_server] */
#define UDP_SERVER_PORT 838

/* 客户端地址 */
static struct sockaddr_in client_addr = {0};
/* 服务端句柄 */
static int server_sock;


static void udp_server_task(void *pvParameters)
{
    struct sockaddr_in server_addr = {0};
    socklen_t client_sock_len;
    int recv_len, err;
    char recv_data[512];

    ESP_LOGE(TAG, "udp_server_task");

    server_sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
    if (server_sock < 0)
    {
        ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
        goto __exit;
    }
    ESP_LOGI(TAG, "Socket created");

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(UDP_SERVER_PORT);

    err = bind(server_sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr));
    if (err < 0)
    {
        ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
        goto __exit;
    }
    ESP_LOGI(TAG, "Socket bound (%s: %d)\n", inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));

    while (1)
    {
        memset(recv_data, 0, sizeof(recv_data));

        recv_len = recvfrom(server_sock,
                            recv_data,
                            sizeof(recv_data),
                            0,
                            (struct sockaddr*)&client_addr,
                            &client_sock_len);

        // ESP_LOGI(TAG, "receive from (%s: %d), size: %d bytes: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), recv_len, recv_data);

        if(recv_len)
        {
            if(enumQueuePushDatas(&g_TypeQueueUdpRead, recv_data, strnlen((char *)recv_data, recv_len)) != queueNormal)
                enumQueueClear(&g_TypeQueueUdpRead);

            vTaskNotifyGiveFromISR(g_TaskNetworkHand, NULL);
        }
    }

__exit:
    ESP_LOGE(TAG, "Shutting down socket");
    shutdown(server_sock, 0);
    close(server_sock);

    vTaskDelete(NULL);
}

void udp_server_init(void)
{
    xTaskCreate(udp_server_task, "udp_server", 2048, (void*)AF_INET, 5, NULL);
}

int8_t udp_datas_send(void *pvDatas, int32_t iLength)
{
    int err;

    if(client_addr.sin_port == 0)
        return 1;

    if ((err = sendto(server_sock, pvDatas, iLength, 0, (struct sockaddr *)&client_addr, sizeof(client_addr))) < 0)
    {
        ESP_LOGE(TAG, "udp_datas_send error: %d", errno);
    }

    return err;
}
